/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.components.pipeline.cards

import cn.nkpro.elcube.annotation.NkNote
import cn.nkpro.elcube.co.spel.NkSpELManager
import cn.nkpro.elcube.docengine.EnumDocClassify
import cn.nkpro.elcube.docengine.NkAbstractCard
import cn.nkpro.elcube.docengine.model.DocDefIV
import cn.nkpro.elcube.docengine.model.DocHV
import cn.nkpro.elcube.docengine.model.DocPipeline
import com.alibaba.fastjson.JSON
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.util.Assert

@Order(2002)
@NkNote("对象结果")
@Component("NkCardPipelineResult")
class NkCardPipelineResult extends NkAbstractCard<Map,Def> {

    @Override
    boolean supports(String classify) {
        return classify == EnumDocClassify.PIPELINE.name()
    }

    @Autowired
    private NkSpELManager spELManager

    @Override
    Map afterGetData(DocHV doc, Map data, DocDefIV defIV, Def d) {
        if(doc instanceof DocPipeline && d.resultSpEL){
            doc.results.putAll(data)
        }
        return super.afterGetData(doc, data, defIV, d) as Map
    }

    @Override
    Map afterUpdated(DocHV doc, Map data, Map original, DocDefIV defIV, Def d) {
        if(doc instanceof DocPipeline && d.resultSpEL){
            doc.results.putAll(data)
        }
        return super.afterUpdated(doc, data, original, defIV, d) as Map
    }

    @Override
    Map calculate(DocHV doc, Map data, DocDefIV defIV, Def d, boolean isTrigger, Object options) {
        if(doc instanceof DocPipeline && d.resultSpEL){
            Object obj = JSON.parse(spELManager.convert(d.resultSpEL, spELManager.createContext(doc)))
            Assert.isTrue(obj instanceof Map,"结果表达式必须返回一个Map实例")
            data = obj as Map
            doc.results.putAll(data)
        }
        return super.calculate(doc, data, defIV, d, isTrigger, options) as Map
    }

    static class Def implements Serializable{
        String resultSpEL
    }
}
